<template>
  <div class="friend">
    <el-card class="box-card">
      <div class="user-item" v-for="(item,index) in data" :key="index">
        <el-badge :id="item.id" :value="item.count" class="item" :hidden="!item.check">
          <div class="user-item" @click="item.check=false;isTalking = true;talk(item.id);toUser=item.id">
            <el-avatar style="height: 40px;width: 40px"
                       :src="item.logoPath"></el-avatar>
            <span style="margin-left: 70px">{{ item.userName }}</span>
          </div>
        </el-badge>
      </div>
    </el-card>

    <el-card class="myCard" style="display: flex;justify-content: center;align-items: center">
      <div style="height: 100%;width: 750px" v-if="isTalking">
        <div id="talk" class="talk"
             style="width: 100%;height: 500px;border: 1px dashed #b4b1b1;margin-bottom: 20px;padding: 20px;box-sizing: border-box;overflow: auto;">
          <div v-for="(item,index) in talkinfo" :key="index" style="height: auto;width: 100%;margin-top: 5px;">
            <div :class="{'left': item.fromuser==item.check, 'right': item.fromuser!=item.check}"
                 style="width:45%;border-radius:8px;height: auto;border: 1px solid #cbc7c7;padding:10px">
              <p v-html="item.msg"></p>
            </div>
            <div class="clear"></div>
          </div>
        </div>
        <el-input placeholder="请输入聊天内容" v-model="input3" class="input-with-select">
          <el-button slot="append" @click="websocketsend" icon="el-icon-position"></el-button>
        </el-input>
      </div>
      <el-empty v-else description="聊天界面"></el-empty>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Friend",
  data() {
    return {
      data: [],
      input3: "",
      talkinfo: [],
      fromUser: null,
      toUser: null,
      isTalking: false,
      websock: undefined,
      isTemporary: false
    }
  },
  created() {
    let id = this.$route.query.touser;
    if (id == undefined) {
      this.getFriend()
    } else {
      this.isTemporary = true
      this.toUser = id
      this.talk(id)
      this.isTalking = true
    }
  },
  destroyed() {
    if (this.websock == undefined) {
      return
    }
    this.websock.close() //离开路由之后断开websocket连接
  },
  methods: {
    talk(id) {
      this.getmsgwhennotsee(id).then(async data => {
        if (data.length == 0) {
          await this.getHimSelf().then(res => {
            this.fromUser = res.id
            this.initWebSocket(res.id)
          })
          this.$nextTick(() => {
            let msg = document.getElementById('talk') // 获取对象
            msg.scrollTop = msg.scrollHeight // 滚动高度
          })
          return
        }
        await data.filter(async (item) => {
          await this.unreadToRead(item.talkid).then(async res => {
            if (res.code == 200) {
              await this.getReadInformation(id).then(async res => {
                await res.filter((ele) => {
                  ele.check = id
                })
                this.talkinfo = res
              })
              await this.getHimSelf().then(res => {
                this.fromUser = res.id
                this.initWebSocket(res.id)
              })
              this.$nextTick(() => {
                let msg = document.getElementById('talk') // 获取对象
                msg.scrollTop = msg.scrollHeight // 滚动高度
              })
            }
          })
        })
      })
    },
    unreadToRead(talkid) {
      return new Promise(resolve => {
        this.$http.put("/talk/unreadToRead/" + talkid).then(data => {
          resolve(data)
        })
      })
    },
    getReadInformation(fromuser) {
      return new Promise(resolve => {
        this.$http.get("/talk/getReadInformation/" + fromuser).then(data => {
          resolve(data.data)
        })
      })
    },
    async initWebSocket(userid) { //初始化weosocket
      console.log("建立连接")
      const wsuri = "ws://127.0.0.1/websocket/" + userid;
      this.url = wsuri
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonmessage(e) { //数据接收
      let redata = JSON.parse(e.data);
      console.log(redata, this.toUser)
      let innimsg = {
        touser: redata.toUser,
        fromuser: redata.fromUser,
        msg: redata.msg,
        check: redata.fromUser
      }
      this.talkinfo.push(innimsg)
      this.$nextTick(() => {
        let msg = document.getElementById('talk') // 获取对象
        msg.scrollTop = msg.scrollHeight // 滚动高度
      })
    },
    async websocketsend() {//数据发送
      let message = {
        toUser: this.toUser,
        fromUser: this.fromUser,
        msg: this.input3
      }
      let innimsg = {
        touser: message.toUser,
        fromuser: message.fromUser,
        msg: message.msg
      }
      this.talkinfo.push(innimsg)
      console.log(this.talkinfo)
      this.websock.send(JSON.stringify(message));
      this.input3 = ""
      this.$nextTick(() => {
        let msg = document.getElementById('talk') // 获取对象
        msg.scrollTop = msg.scrollHeight // 滚动高度
      })
    },
    websocketonopen() { //连接建立之后执行send方法发送数据

    },
    websocketonerror() {//连接建立失败重连
      // this.initWebSocket();
    },
    websocketclose(e) {  //关闭
      console.log(e)
      console.log('断开连接');
    },
    getmsgwhennotsee(fromuser) {
      return new Promise(resolve => {
        this.$http.get("/talk/getmsg/" + fromuser).then(data => {
          resolve(data.data)
        })
      })
    },
    getHimSelf() {
      return new Promise(resolve => {
        this.$http.get("/login/getUserHimself").then(res => {
          resolve(res.data)
        })
      })
    },
    async getFriend() {
      await this.$http.get("/talk/selectByMyself").then(async data => {
        data = data.data
        for (let i = 0; i < data.length; i++) {
          await this.getImg(data[i].logo).then(res => {
            data[i].logoPath = res
          })
          await this.$http.post("/talk/getall").then(async response => {
            let res = response.data
            data[i].count = 0
            await res.filter(item => {
              if (item.fromuser == data[i].id) {
                data[i].count++
                data[i].check = true
              }
            })
          })
        }
        this.data = data
      })
    },
    getImg(id) {
      return new Promise(resolve => {
        this.$http({
          url: "/file/img/" + id,
          method: "get",
          responseType: "arraybuffer",
        }).then(res => {
          let bytes = new Uint8Array(res);
          let storeData = "";
          let len = bytes.byteLength;
          for (let i = 0; i < len; i++) {
            storeData += String.fromCharCode(bytes[i]);
          }
          let database = "data:image/png;base64," + window.btoa(storeData);
          resolve(database);
        });
      })
    },
  }
}
</script>

<style scoped>
.friend {
  width: 980px;
  float: right;
}

.box-card {
  width: 200px;
  min-height: 450px;
  display: flex;
  flex-direction: column;
  float: left;
}

.myCard {
  width: 760px;
  height: 600px;
  margin-left: 15px;
  float: left;
}

.user-item {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  border-bottom: 1px solid #eaeaea;
  cursor: pointer;
}

.clear {
  clear: both;
}

.left {
  float: left;
}

.right {
  float: right;
}

.el-table .cell {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  white-space: normal;
  word-break: break-all;
  line-height: 23px;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: nowrap !important;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>